﻿<script setup lang="ts" name="WebsocketTest">
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { useUserInfoStoreWithOut } from '@/store/storage/userInfoStore'
import useSocket from '@/utils/websocket/useSocket'
import { socketOptions } from '@/utils/websocket/utils'
import { cloneDeep } from 'lodash-es'
import dayjs from 'dayjs'
const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)
const userInfoStore = useUserInfoStoreWithOut()
const { userInfo } = storeToRefs(userInfoStore)
const route = useRoute()
// 获取当前页面的缓存状态是否被开启
const isKeepAlive = route.meta.keepAlive && systemConfig.value.isKeepAlive

const initInfo = ref({
  t: 0,
  data: null
})
const onMessageCallback = (res: any) => {
  console.log(res)
  if (res.type === 'test' && res.sendtime === initInfo.value.t) {
    // 执行相关逻辑
    initInfo.value.data = res.data
  }
}
const { initSocket, close } = useSocket(onMessageCallback)
const testSocket: any = ref(null)
testSocket.value = cloneDeep(socketOptions())
// 在组件挂载到页面后执行
onMounted(() => {
  // 未开启页面状态缓存的情况下，监听事件在此声明周期内开启
  if (!isKeepAlive) {
    // 启动websocket通信
    initInfo.value.t = new Date(dayjs().format()).getTime()
    testSocket.value.message = {
      type: 'test',
      uid: userInfo.value.id,
      sendtime: initInfo.value.t
    }
    initSocket(testSocket)
  }
})
// 页面未启用keep-alive时，则需要在此生命周期函数内（组件被卸载之前执行）移除监听
onBeforeUnmount(() => {
  // 未开启页面状态缓存的情况下，监听事件在此声明周期内移除
  if (!isKeepAlive) {
    // 关闭websocket通信
    close(testSocket)
  }
})

// keep-alive启用时，页面被激活时使用
onActivated(() => {
  // 开启页面状态缓存的情况下，监听事件在此声明周期内开启
  if (isKeepAlive) {
    // 启动websocket通信
    initInfo.value.t = new Date(dayjs().format()).getTime()
    testSocket.value.message = {
      type: 'test',
      uid: userInfo.value.id,
      sendtime: initInfo.value.t
    }
    initSocket(testSocket)
  }
})
// 页面启用keep-alive时，则需要在此生命周期函数内（组件切换，老组件消失的时候执行）移除监听事件
onDeactivated(() => {
  // 开启页面状态缓存的情况下，监听事件在此声明周期内移除
  if (isKeepAlive) {
    // 关闭websocket通信
    close(testSocket)
  }
})
</script>
<template>
  <el-space :size="systemConfig.space" fill direction="vertical">
    <el-card shadow="never" class="no-border no-radius">
      <h2>websocket测试</h2>
    </el-card>
  </el-space>
</template>

<style scoped lang="scss">
.el-space {
  width: 100%;
  padding: var(--el-space) var(--el-space) 0;
}

.no-border {
  border: none;
}

.no-radius {
  border-radius: 0;
}

h2 {
  font-weight: bold;
  font-size: 24px;
}

.el-card {
  display: flex;

  :deep(.el-card__body) {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    p {
      margin-top: 10px;
      text-align: center;
    }
  }
}
</style>
